<?php
/**
 * OAuth客户端模块
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Model
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/easyaccount/license
 */
namespace ea\model;

use ea\library\Cache;

class OAuthClient {
	/**
	 * 获取名称对应的ID
	 * @access public
	 * @param string $name
	 * @return int
	 */
	public static function getId($name) {
		$class = self::getClassName($name);
		if (class_exists($class)) {
			return -1;
		} else {
			return $class::ID;
		}
	}
	/**
	 * 获取当前列表
	 * @param bool $rescan 是否重新扫描OAuthClient文件夹
	 * @return array
	 */
	public static function list($rescan = FALSE) {
		$client = Cache::get('oauth_client');
		if ($client) {
			$client = swoole_unserialize($client);
		}
		if (!$client || $rescan) {
			$dh = opendir(APP_PATH . 'library/OAuthClient');
			while ($f = readdir($dh)) {
				if ($f === '.' || $f === '..' || $f === 'OAuthInterface.php') {
					continue;
				}
				$name = substr($f, 0, strpos($f, '.'));
				if (isset($client[$name])) {
					continue;
				}
				$id = self::getId($name);
				$client[$id] = [
					'name' => $name,
					'enable' => 0,
					'client_id' => '',
					'client_secret' => ''
				];
			}
			@closedir($dh);
			Cache::set('oauth_client', swoole_serialize($client));
		}
		return $client;
	}
	/**
	 * 设置单个项目信息
	 * @param int/string $name
	 * @return array
	 */
	public static function get($name) {
		if (!is_numeric($name)) {
			$name = self::getId($name);
		}
		$client = self::list();
		return isset($client[$name]) ? $client[$name] : NULL;
	}
	/**
	 * 设置单个项目
	 * @param int/string $name
	 * @param array $options
	 */
	public static function set($name, $options) {
		if (!is_numeric($name)) {
			$name = (self::getClassName($name))::ID;
		}
		$client = self::list();
		foreach ($options as $k => $v) {
			$client[$name][$k] = is_numeric($v) ? intval($v) : $v;
		}
		Kv::set('oauth_client', $client);
	}
	/**
	 * 获取完整类名
	 * @param string $name
	 * @return string
	 */
	public static function getClassName($name) {
		return '\\ea\\library\\OAuthClient\\' . $name;
	}
	/**
	 * 加密字符串
	 * @access public
	 * @param mixed $info
	 * @param boolean $is_decrpty
	 * @return mixed
	 */
	public static function encrypt($info, $is_decrpty = FALSE) {
		static $secret = NULL;
		static $len = 0;
		if ($secret === NULL) {
			$secret = str_split(Config::getInstance()->read('oauth_secret'), 1);
			foreach ($secret as $k => $v) {
				$secret[$k] = ord($v);
			}
			$len = count($secret);
		}
		$result = '';
		if ($is_decrpty) {
			foreach (str_split(base64_decode($info), 1) as $k => $v) {
				$result .= chr(ord($v) ^ $secret[$k % $len]);
			}
			return swoole_unserialize($result);
		} else {
			$info = str_split(swoole_serialize($info), 1);
			foreach ($info as $k => $v) {
				$result .= chr(ord($v) ^ $secret[$k % $len]);
			}
			return base64_encode($result);
		}
	}
}